import { createStore } from 'redux';

const reducer = (state, action) => {
    console.log(action, 'action')
    if (action.type === 'HTTP') {
        return { ...state, list: action.list }
    } else if (action.type === 'ADD') {
        const arr = state.list.map(item => {
            if (item.id === action.id) {
                item.num += 1
            }
            return item;
        })
        return { ...state, list: arr }
    } else if (action.type === 'DIS') {
        const arr = state.list.map(item => {
            if (item.id === action.id && item.num > 0) {
                item.num -= 1
            }
            return item;
        })
        return { ...state, list: arr }
    } else if (action.type === 'CHECKED') {
        const arr = state.list.map(item => {
            if (item.id === action.id) {
                item.ischeckBox = action.checked
            }
            return item;
        })

        return { ...state, list: arr }
    } else if (action.type === 'PRICE') {
        const priceAll = state.list.reduce((price, item) => {
            return price + (item.ischeckBox ? item.num * item.price : 0)
        }, 0)

        return { ...state, totalPrice: priceAll }
    } else if (action.type === 'CHECK_ALL') {
        const arr = state.list.map(item => {
            item.ischeckBox = action.checked;
            return item;
        })
        return { ...state, list: arr, allChecked: action.checked }
    }
    return { ...state }
}

let initalState = {
    list: [],
    totalPrice: 0,
    allChecked: false
}

const store = createStore(reducer, initalState);

export default store;